package com.zy.mc_module.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.SystemClock;
import android.text.*;
import android.text.style.ForegroundColorSpan;
import android.text.style.LeadingMarginSpan;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.text.TextUtils;

import com.haibin.calendarview.Calendar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.zy.mc_module.R;
import com.zy.mc_module.base.App;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created on 18/10/20
 * App工具类
 */
public class AppTools {
    //--------------------------------------------APP 环境切换------------------------------------------------------
    //--------------------------------------------APP 环境切换------------------------------------------------------

    /**
     * 切换app环境的sharePreferenc的key
     */
    public static final String APP_URL_CHANGE = "app_url_change";
    public static final int APP_URL_TYPE_DEV = 0;//开发254
    public static final int APP_URL_TYPE_TEST = 1;//测试239
    public static final int APP_URL_TYPE_PRETEST = 2;//预发
    public static final int APP_URL_TYPE_ONLINE = 3;
    public static final int APP_URL_TYPE_AUTO = 4;

    //网络请求地址
    public static String Base_Url;
    public static final String APP_URL_ONLINE = "https://api.315bzsc.com/";//正式
    public static final String APP_URL_PRETEST = "http://api.swybeta.315swy.cn/";//"https://api.315swy.cn/";//预发
    public static final String APP_URL_DEV = "http://api.swydev151.315swy.cn/";//"http://192.168.50.254/";//"http://api.dev.315swy.cn/";//开发
    public static final String APP_URL_TEST = "http://api.test.wanminzg.cn/";//"http://192.168.50.239/";//测试
    //分享地址
    public static String share_Url;
    public static final String APP_SHARE_URL_ONLINE = "https://mobile.315bzsc.com/";//正式
    public static final String APP_SHARE_URL_PRETEST = "http://h5.swybeta.315swy.cn/";//"https://mobile.315swy.cn/";//预发
    public static final String APP_SHARE_URL_DEV = "http://h5.swydev151.315swy.cn/";//"http://192.168.50.254/";////"http://h5.dev.315swy.cn/";//开发
    public static final String APP_SHARE_URL_TEST = "http://h5.swytest.315swy.cn/";//"http://192.168.50.239/";//测试
    //申请信用卡地址
    public static String Base_Card_Url;
    public static final String APP_CARD_URL = "http://jksdadmin.91bicheng.com/h5/home?";//http://mobile.91bicheng.com/
    public static final String APP_CARD_TEST_URL = "http://192.168.50.254:8081/h5/home?";

    //--------------------------------------------APP 环境切换------------------------------------------------------
    //--------------------------------------------APP 环境切换------------------------------------------------------

    public static String APP_CHANNEL = "swy";//渠道号,测试渠道号swy_test

    public static String kf_tel = "";//客服电话号码
    public static String integralName = "";//积分名称
    public static String integralTypeId = "";//积分id
    public static String exchangeIntegralIcon = "";//积分logo
    public static String exchangeIntegralRules = "";//积分规则
    public static String deductionIntegralName = "";//抵扣积分名称 金币
    public static String deductionIntegralId = "";//抵扣积分id 金币
    public static String deductionIntegralIcon = "";//抵扣积分logo
    public static String deductionIntegralRules = "";
    public static String nearCashIntegralName = "";//类现金积分名称 优豆
    public static String nearCashIntegralId = "";//类现金积分id 优豆
    public static String nearCashIntegralIcon = "";//类现金logo
    public static String nearCashIntegralRules = "";
    public static String redEnvelopesIntegralId = "";//红包id
    public static String redEnvelopesIntegralName = "";//红包名称
    public static String redEnvelopesIntegralIcon = "";//红包logo
    public static String redEnvelopesIntegralRules = "";
    public static String allowanceId = "";//津贴id
    public static String allowanceName = "";//津贴名称
    public static String allowanceIntegralIcon = "";//津贴logo
    public static String allowanceIntegralRules = "";//津贴规则

    public static String orderNo;//取消订单的编号

    public static boolean credit_card_repayment_invoke_config;
    public static String credit_card_repayment_invoke_config_bg;
    public static boolean invite_receive_gifts_invoke_config;
    public static boolean partner_invoke_config;

    //连续点击
    private static long[] mHits = null;
    private static boolean mShow = false;

    //搜索--城市列表选择的城市的编号
    public static String areaNo = "";
    //搜索--关键字
    public static String keyword = "";
    //筛选--入住日期
    public static Calendar calendar;
    //筛选--入住日期当前页数
    public static int date_page;

    //文章Tab当前位置
    public static int findTab = 0;

    //是否显示通用布局
    public static boolean isShowBase = true;

    public static int page = 10;//列表每页所加载的数据

    public static int type = 0;//分享的类型 3分享文章  4分享商品
    public static String shareId;//分享的id

    /***
     * 倒计时工具
     * 时间单位毫秒
     */
    public static Observable<Integer> countdown(int time, TimeUnit timeUnit) {
        if (time < 0) {
            time = 0;
        }
        int countTime = time;
        return Observable.interval(0, 1, timeUnit)
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .map(aLong -> countTime - aLong.intValue())
                .take(countTime + 1);
    }

    /***
     * 一个TextView展示不同颜色的文字
     * @param text  不改变颜色的文字
     * @param colortext  需要改变颜色的文字
     * @param color 颜色
     * @return
     */
    public static SpannableString colorText(String text, String colortext, String color) {
        SpannableString spannableString = new SpannableString(text + colortext);
        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor(color)), text.length(),
                spannableString.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    /***
     * Html展示文本,不能修改大小
     * @param centre 需要改变颜色的文字
     * @param left 左边不改变颜色的文字
     * @param right 右边不改变颜色的文字
     * @param color 颜色
     * @return
     */
    public static Spanned htmlText(String centre, String left, String right, String color) {
        return Html.fromHtml(left + "<font color='" + color + "'>" + centre + "</FONT>" + right);

    }

    /***
     * 单独判断:是手机号才设置颜色
     */
    public static Spanned htmlTel(String con, String tel, String color) {
        if (null == tel) {
            tel = "";
        }
        return Html.fromHtml(con + "<font color='" + color + "'>" + tel + "</FONT>");
    }

    /***
     * Edittext 显示/隐藏密码
     */
    public static void hidePwd(EditText editText, boolean isChecked) {
        if (isChecked) {
            //显示明文
            editText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            editText.setSelection(editText.getText().length());
        } else {
            //默认状态显示密码
            editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType
                    .TYPE_TEXT_VARIATION_PASSWORD);
            editText.setSelection(editText.getText().length());
        }
    }

    /***
     * 连续点击
     */
    public static boolean continuous(int time) {
        // 需要点击几次 就设置几
        try {
            if (mHits == null) {
                mHits = new long[time];
            }
            System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
            mHits[mHits.length - 1] = SystemClock.uptimeMillis();//记录一个时间
            if (SystemClock.uptimeMillis() - mHits[0] <= 1000) {
                //一秒内连续点击。
                mHits = null;
                mShow = !mShow;
            } else {
                mShow = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return mShow;
        }
        return mShow;
    }

    /***
     * getIntent 是否有key
     */
    public static String getHasKeyS(Activity activity, String key) {
        if (null != activity && activity.getIntent().hasExtra(key)) {
            return activity.getIntent().getStringExtra(key);
        } else {
            return "";
        }
    }

    /***
     * 手动处理density,解决部分手机webview高度异常
     * 0.75/1.5/2/3
     */
    public static float getDensity(float density) {
        if (density <= 3) {
            if (density >= 0.5 && density <= 0.75) {
                density = 0.75f;
            } else if (density > 1.2 && density <= 1.5) {
                density = 1.5f;
            } else if (density > 1.6 && density <= 2) {
                density = 2f;
            } else if (density > 2.6 && density <= 3) {
                density = 3f;
            }
        }
        return density;
    }

    /***
     * 去掉小数点后面多余的0
     */
    public static String removeTrim(Object object) {
        try {
            String str = object.toString();
            if (str.indexOf(".") > 0) {
                str = str.replaceAll("0+?$", "");//去掉多余的0
                str = str.replaceAll("[.]$", "");//如最后一位是.则去掉
            }
            return str;
        } catch (Exception e) {
            e.printStackTrace();
            return "0";
        }
    }

    /***
     * 小数点保留两位小数
     */
    public static String decimalsT(Object object) {
        try {
            String str = object.toString();
            BigDecimal bd = new BigDecimal(str);
            return bd.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "0.00";
        }
    }

    /***
     * 转换webview中的\n  \r
     */
    public static String replaceCon(String str) {
        if (null != str) {
            //"\n"替换为"<br>
            return str.replace("\n", "<br>");
        } else {
            return "";
        }
    }

    /***
     * List<String> 转String
     */
    public static String listToString(List<String> lists, CharSequence target, CharSequence
            replacement) {
        String con = "";
        if (null != lists) {
            con = GsonUtil.gsonString(lists).replace("\"", "").replace("[", "").replace("]", "")
                    .replace(target, replacement);
        }
        return con;
    }

    /***
     * 移除List<String>集合中的空""数据
     */
    public static ArrayList<String> trimList(List<String> strings) {
        ArrayList<String> list = new ArrayList<>();
        for (String string : strings) {
            if (!TextUtils.isEmpty(string)) {
                list.add(string);
            }
        }
        return list;
    }

    /***
     * int颜色转RGB
     */
    public static int[] colorToRGB(int color) {
        int red = (color & 0xff0000) >> 16;
        int green = (color & 0x00ff00) >> 8;
        int blue = (color & 0x0000ff);
        return new int[]{red, green, blue};
    }

    /***
     * 订单跟踪的文字颜色显示
     */
    public static void setOrderTrackingText(Context context, TextView textView, String con, int pos) {
        if (pos == 0) {
            textView.setTextColor(Color.parseColor("#333333"));
        } else {
            textView.setTextColor(Color.parseColor("#999999"));
        }
        SpannableStringUtil.setTelUrl(context, textView, con);
    }

    /***
     * 设置View间隔
     */
    public static void setMargin(View view, int l, int t, int r, int b) {
        if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
            p.setMargins(l, t, r, b);
            view.requestLayout();
        }
    }

    /***
     * 下拉刷新结束
     */
    public static void finishRefresh(SmartRefreshLayout refreshLayout) {
        if (null != refreshLayout && refreshLayout.getState().isOpening) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
        }
    }

    /**
     * EditText竖直方向是否可以滚动
     *
     * @param editText 需要判断的EditText
     * @return true：可以滚动   false：不可以滚动
     */
    public static boolean canVerticalScroll(EditText editText) {
        //滚动的距离
        int scrollY = editText.getScrollY();
        //控件内容的总高度
        int scrollRange = editText.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() - editText
                .getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if (scrollDifference == 0) {
            return false;
        }
        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }

    /***
     * 截取文本
     * @return
     */
    public static String cutText(String str, int length) {
        if (TextUtils.isEmpty(str)) {
            return "";
        } else {
            if (str.length() > length) {
                return str.substring(0, length) + "...";
            } else {
                return str;
            }
        }
    }

    /**
     * 首行缩进的SpannableString
     *
     * @param description 描述信息
     */
    public static SpannableString getSpannableString(Context context, String description) {
        SpannableString spannableString = new SpannableString(description);
        int marginSpanSize = SizeUtils.dp2px(context, 30 + 3);//文字宽度+ 背景padding4dp+间隔3dp
        LeadingMarginSpan leadingMarginSpan = new LeadingMarginSpan.Standard(marginSpanSize, 0);//仅首行缩进
        spannableString.setSpan(leadingMarginSpan, 0, description.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    /**
     * 首行缩进的SpannableString
     *
     * @param description 描述信息
     */
    public static SpannableString getSpannableString(Context context, String description, int size) {
        SpannableString spannableString = new SpannableString(description);
        int marginSpanSize = SizeUtils.dp2px(context, size * 18);//文字宽度+ 背景padding4dp+间隔3dp
        LeadingMarginSpan leadingMarginSpan = new LeadingMarginSpan.Standard(marginSpanSize, 0);//仅首行缩进
        spannableString.setSpan(leadingMarginSpan, 0, description.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    public static String getDeductionIntegralName() {
        return StringsUtils.isEmpty(deductionIntegralName) ? "优豆" : deductionIntegralName;
    }

    public static String hidePhone(String phone) {
        if (StringsUtils.isMobile(phone)) {
            return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        } else return phone;

    }
}
